import Zombies
import Plantes
import pygame as pg
import threading
import time
import copy
import os
import queue
import random
startTime=int(time.time())
pg.init()
clock = pg.time.Clock()
screen = pg.display.set_mode((800,600))
pg.display.set_caption("植物大战僵尸")
icon = pg.image.load("images\screenshot1.jpg")
pg.display.set_icon(icon)
backgroung_img = pg.image.load("images\\background1.jpg")
SeedBank_img = pg.image.load("images\\SeedBank.png")
SeedPacket_Larger_img = pg.image.load("images\SeedPacket_Larger.png")
try:
    pg.mixer.music.load('audio\\BGMusic.mp3')
    pg.mixer.music.play(loops=-1)
except:
    pass



class SoundEffect:
    def __init__(self):
        self.launch=pg.mixer.Sound("audio\\launch.mp3")
try:
    soundEffect=SoundEffect()
except:
    pass
score = 0
sun = 0

player = Plantes.PeaShooter()
Bean = []
Zombie = []

isWin=None

# def distance(bx,by,ex,ey):
#     a = bx - ex
#     b = by - ey
#     return math.sqrt(a*a+b*b)

def draw_SeedBank():
    screen.blit(SeedBank_img,(0,0))

def draw_img():
    screen.blit(backgroung_img,(-220,0))
    screen.blit(player.img,(player.x,player.y))

def draw_Beans(): 
    for b in Bean:
        screen.blit(b.img,(b.x,b.y))

def draw_Zombie():
    for e in Zombie:
        pg.draw.rect(screen,(255,255,255),(e.x,e.y-40,40,10),2)
        pg.draw.rect(screen, e.healthbarColor, [e.x+2,e.y-38,e.healthy/e.maxhealthy*36,6],0)
        screen.blit(e.img,(e.x,e.y-35))

font=pg.font.Font("fonts/title.ttf", 180)
countDownFont=pg.font.Font("fonts/countDown.ttf", 64)
sunFont=pg.font.Font("fonts/countDown.ttf", 24)

def draw_sun():
    try:
        sun_render = sunFont.render(f"{sun}",True,(0,0,0))
    except:
        os._exit(0)
    screen.blit(sun_render,(15,60))

def drawContDown():
    countDown=countDownFont.render(str(150+startTime-int(time.time())),1,(255,0,0))
    screen.blit(countDown,(700,10))

def draw():
    global isWin
    try:
        while True:
            clock.tick(60)
            if isWin!=None:
                break
            draw_img()
            draw_SeedBank()
            draw_sun()
            draw_Beans()
            draw_Zombie()
            drawContDown()
            pg.display.update()
        if isWin:
            while True:
                clock.tick(60)
                screen.fill((215,119,6))
                winTips=font.render("胜利",1,(255,255,255))
                screen.blit(winTips,(200,200))
                pg.display.update()
        else:
            while True:
                clock.tick(60)
                screen.fill((104,33,122))
                lossTips=font.render("失败",1,(255,255,255))
                screen.blit(lossTips,(200,200))
                pg.display.update()
    except:
        os._exit(1)

def doKeyEvent(key):
    if key == pg.K_RIGHT and player.x < (8 * 80) + 25:
        player.x += 80
    elif key == pg.K_LEFT and player.x > (1 * 80) + 25:
        player.x += -80
    elif key == pg.K_UP and player.y > (1 * 80) + 25:
        player.y += -100
    elif key == pg.K_DOWN and player.y < (5 * 80) + 25:
        player.y += 100
    elif key == pg.K_SPACE:
        Bean.append(player.bullet(player))
        try:
            soundEffect.launch.play()
        except:
            pass

def logic():
    global Bean,isWin
    i=0
    while True:
        clock.tick(150)
        if int(time.time())-startTime>150:
            isWin = True
        if isWin!=None:
            return
        i=(i+1)%15
        if not i:
            for key in copy.copy(keyList):
                if keyList.get(key) == None or float(time.time()) - keyList.get(key) < 0.3:
                    continue
                doKeyEvent(key)
        while not keyDownList.empty():
            doKeyEvent(keyDownList.get())
        for e in Zombie:
            e.x += e.speed
            if e.x < 0:
                isWin=False
        Bean = list(filter(None, Bean))
        if len(Zombie)<=15 and random.randint(1,max(50,135-int(time.time())+startTime))==1:
            Zombie.append(Zombies.Zombie())
        for b in Bean:
            if b.hit(Zombies=Zombie,Beans=Bean):
                try:
                    Bean.remove(b)
                except:
                    pass
            b.move()
            if b.x > 800 or b.x < 0 or b.y < -50 or b.y > 650:
                try:
                    Bean.remove(b)
                except:
                    break
                break
        



渲染 = threading.Thread(target=draw,name= "渲染",daemon=True)
逻辑 = threading.Thread(target=logic,name = "逻辑",daemon=True)
渲染.start()
逻辑.start()

keyList={}
keyDownList=queue.Queue()
while True:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            pg.quit()
            quit()
        if event.type == pg.KEYDOWN:
            keyList[event.key]=float(time.time())
            keyDownList.put(event.key)
            if event.key == pg.K_1:
                player = Plantes.PeaShooter(player.x,player.y)
            elif event.key == pg.K_2:
                player = Plantes.sinPeaShooter(player.x,player.y)
            elif event.key == pg.K_3:
                player = Plantes.bombPeaShooter(player.x,player.y)
            # elif event.key == pg.K_4:
            #     player = Plantes.sinBombPeaShooter(player.x,player.y)
        if event.type == pg.KEYUP:
            del keyList[event.key]
    # show_sun()